package com.test.case5;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author:wyf
 * @Description:
 * @Date:Created in 13:48 2021/6/29
 * @Modified By:
 */
public class Counter12 {
    // 请求总数
    public static int clientTotal = 100000000;

    // 同时并发执行的线程数
    public static int threadTotal = 1000;
    public static AtomicLong count = new AtomicLong(0);

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 10; i++) {
            count.set(0);
            count();
        }
    }

    private static void count() throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        //信号量，只允许threadTotal个线程同时访问
        final Semaphore semaphore = new Semaphore(threadTotal);

        long t1 = System.currentTimeMillis();
        for (int i = 0; i < clientTotal ; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();//acquire()用于请求信号，每调用一次，信号量便少一个
                    add();
                    semaphore.release();//release()用于释放信号，调用一次信号量加一个
                } catch (Exception e) {

                }

            });

//            executorService.submit(new Runnable() {
//                @Override
//                public void run() {
//                    try {
//                        semaphore.acquire();
//                        add();
//                        semaphore.release();
//                    } catch (Exception e) {
//
//                    }
//                }
//            });
        }
        executorService.shutdown();
        long t2 = System.currentTimeMillis();
        System.out.println("Counter12 , "+String.format("结果：%s,耗时(ms)：%s", count.get(), (t2 - t1)));

    }

    private static void add() {
        count.getAndIncrement();
    }

}
